import React, { useState, useMemo } from 'react';
import { useNavigate } from 'react-router-dom';
import {
  Box,
  Card,
  CardContent,
  Typography,
  Button,
  IconButton,
  TextField,
  FormControl,
  InputLabel,
  Select,
  MenuItem,
  Grid,
  Chip,
  Menu,
  Paper,
  List,
  ListItem,
  ListItemText,
  ListItemIcon,
  ListItemButton,
  Collapse,
  Switch,
  FormControlLabel,
  Tooltip,
  Alert,
  TreeView,
  TreeItem,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Divider,
  Avatar
} from '@mui/material';
import {
  Add as AddIcon,
  Search as SearchIcon,
  MoreVert as MoreVertIcon,
  AccountTree as AccountTreeIcon,
  Business as BusinessIcon,
  Group as GroupIcon,
  Edit as EditIcon,
  Delete as DeleteIcon,
  ExpandMore as ExpandMoreIcon,
  ChevronRight as ChevronRightIcon,
  Refresh as RefreshIcon,
  Download as DownloadIcon,
  Upload as UploadIcon,
  ViewList as ViewListIcon,
  AccountBalance as AccountBalanceIcon
} from '@mui/icons-material';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { useForm, Controller } from 'react-hook-form';
import { PageHeader } from '@/components/common/PageHeader';
import { departmentService } from '@/services/departmentService';
import type { Department, CreateDepartmentRequest } from '@/types';

interface DepartmentTreeNode extends Department {
  children?: DepartmentTreeNode[];
}

interface CreateDepartmentFormData {
  name: string;
  code: string;
  description?: string;
  parentId?: string;
  managerId?: string;
  status: 'active' | 'inactive';
}

const DepartmentListPage: React.FC = () => {
  const navigate = useNavigate();
  const queryClient = useQueryClient();
  const [searchTerm, setSearchTerm] = useState('');
  const [selectedStatus, setSelectedStatus] = useState<string>('all');
  const [viewMode, setViewMode] = useState<'tree' | 'list'>('tree');
  const [anchorEl, setAnchorEl] = useState<null | HTMLElement>(null);
  const [selectedDepartment, setSelectedDepartment] = useState<Department | null>(null);
  const [createDialogOpen, setCreateDialogOpen] = useState(false);
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
  const [expandedNodes, setExpandedNodes] = useState<string[]>(['root']);

  const {
    control,
    handleSubmit,
    reset,
    setValue,
    watch,
    formState: { errors, isValid }
  } = useForm<CreateDepartmentFormData>({
    defaultValues: {
      name: '',
      code: '',
      description: '',
      parentId: '',
      managerId: '',
      status: 'active'
    },
    mode: 'onChange'
  });

  // 获取部门列表
  const { data: departments = [], isLoading } = useQuery({
    queryKey: ['departments'],
    queryFn: () => departmentService.getDepartments({})
  });

  // 创建部门
  const createDepartmentMutation = useMutation({
    mutationFn: (data: CreateDepartmentRequest) => departmentService.createDepartment(data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['departments'] });
      setCreateDialogOpen(false);
      reset();
    }
  });

  // 删除部门
  const deleteDepartmentMutation = useMutation({
    mutationFn: (id: string) => departmentService.deleteDepartment(id),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['departments'] });
      setDeleteDialogOpen(false);
      setSelectedDepartment(null);
    }
  });

  // 构建部门树
  const departmentTree = useMemo(() => {
    const buildTree = (parentId: string | null = null): DepartmentTreeNode[] => {
      return departments
        .filter((dept: Department) => dept.parentId === parentId)
        .map((dept: Department) => ({
          ...dept,
          children: buildTree(dept.id)
        }));
    };
    return buildTree();
  }, [departments]);

  // 过滤部门
  const filteredDepartments = useMemo(() => {
    return departments.filter((dept: Department) => {
      const matchesSearch = !searchTerm ||
        dept.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
        dept.code.toLowerCase().includes(searchTerm.toLowerCase()) ||
        dept.description?.toLowerCase().includes(searchTerm.toLowerCase());
      
      const matchesStatus = selectedStatus === 'all' || dept.status === selectedStatus;
      
      return matchesSearch && matchesStatus;
    });
  }, [departments, searchTerm, selectedStatus]);

  // 渲染部门树节点
  const renderTreeNode = (node: DepartmentTreeNode) => {
    const hasChildren = node.children && node.children.length > 0;
    
    return (
      <TreeItem
        key={node.id}
        nodeId={node.id}
        label={
          <Box sx={{ display: 'flex', alignItems: 'center', py: 1 }}>
            <Avatar sx={{ width: 32, height: 32, mr: 2, bgcolor: 'primary.main' }}>
              <BusinessIcon fontSize="small" />
            </Avatar>
            <Box sx={{ flexGrow: 1 }}>
              <Typography variant="body1" sx={{ fontWeight: 'medium' }}>
                {node.name}
              </Typography>
              <Typography variant="caption" color="text.secondary">
                {node.code} • {node.userCount || 0} 名成员
              </Typography>
            </Box>
            <Box sx={{ display: 'flex', gap: 1 }}>
              <Chip
                label={node.status === 'active' ? '正常' : '停用'}
                size="small"
                color={node.status === 'active' ? 'success' : 'default'}
                variant="outlined"
              />
              <IconButton
                size="small"
                onClick={(e) => {
                  e.stopPropagation();
                  setSelectedDepartment(node);
                  setAnchorEl(e.currentTarget);
                }}
              >
                <MoreVertIcon fontSize="small" />
              </IconButton>
            </Box>
          </Box>
        }
      >
        {hasChildren && node.children!.map(child => renderTreeNode(child))}
      </TreeItem>
    );
  };

  // 渲染列表视图
  const renderListView = () => (
    <Grid container spacing={2}>
      {filteredDepartments.map((dept: Department) => {
        const parentDept = departments.find((d: Department) => d.id === dept.parentId);
        return (
          <Grid item xs={12} sm={6} md={4} key={dept.id}>
            <Card
              sx={{
                cursor: 'pointer',
                '&:hover': { boxShadow: 4 }
              }}
              onClick={() => {
                // 点击查看部门详情
              }}
            >
              <CardContent>
                <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', mb: 2 }}>
                  <Avatar sx={{ bgcolor: 'primary.main' }}>
                    <BusinessIcon />
                  </Avatar>
                  <IconButton
                    size="small"
                    onClick={(e) => {
                      e.stopPropagation();
                      setSelectedDepartment(dept);
                      setAnchorEl(e.currentTarget);
                    }}
                  >
                    <MoreVertIcon />
                  </IconButton>
                </Box>
                
                <Typography variant="h6" sx={{ mb: 1 }}>
                  {dept.name}
                </Typography>
                
                <Typography variant="body2" color="text.secondary" sx={{ mb: 2 }}>
                  {dept.description || '暂无描述'}
                </Typography>
                
                <Box sx={{ display: 'flex', flexDirection: 'column', gap: 1 }}>
                  <Box sx={{ display: 'flex', justifyContent: 'space-between' }}>
                    <Typography variant="caption" color="text.secondary">
                      部门代码
                    </Typography>
                    <Typography variant="caption">
                      {dept.code}
                    </Typography>
                  </Box>
                  
                  {parentDept && (
                    <Box sx={{ display: 'flex', justifyContent: 'space-between' }}>
                      <Typography variant="caption" color="text.secondary">
                        上级部门
                      </Typography>
                      <Typography variant="caption">
                        {parentDept.name}
                      </Typography>
                    </Box>
                  )}
                  
                  <Box sx={{ display: 'flex', justifyContent: 'space-between' }}>
                    <Typography variant="caption" color="text.secondary">
                      成员数量
                    </Typography>
                    <Typography variant="caption">
                      {dept.userCount || 0} 人
                    </Typography>
                  </Box>
                  
                  <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                    <Typography variant="caption" color="text.secondary">
                      状态
                    </Typography>
                    <Chip
                      label={dept.status === 'active' ? '正常' : '停用'}
                      size="small"
                      color={dept.status === 'active' ? 'success' : 'default'}
                      variant="outlined"
                    />
                  </Box>
                </Box>
              </CardContent>
            </Card>
          </Grid>
        );
      })}
    </Grid>
  );

  const handleMenuClick = (event: React.MouseEvent<HTMLElement>) => {
    setAnchorEl(event.currentTarget);
  };

  const handleMenuClose = () => {
    setAnchorEl(null);
    setSelectedDepartment(null);
  };

  const handleCreateDepartment = (data: CreateDepartmentFormData) => {
    createDepartmentMutation.mutate({
      ...data,
      parentId: data.parentId || null
    });
  };

  const handleDeleteDepartment = () => {
    if (selectedDepartment) {
      deleteDepartmentMutation.mutate(selectedDepartment.id);
    }
  };

  // 根据名称自动生成部门代码
  const deptName = watch('name');
  React.useEffect(() => {
    if (deptName) {
      const code = deptName
        .toLowerCase()
        .replace(/[\s\u4e00-\u9fa5]/g, '_')
        .replace(/[^a-z0-9_]/g, '')
        .replace(/_+/g, '_')
        .replace(/^_|_$/g, '');
      setValue('code', code.toUpperCase());
    }
  }, [deptName, setValue]);

  return (
    <Box sx={{ p: 3 }}>
      <PageHeader
        title="部门管理"
        description="管理组织架构和部门信息"
        action={
          <Box sx={{ display: 'flex', gap: 1 }}>
            <FormControlLabel
              control={
                <Switch
                  checked={viewMode === 'tree'}
                  onChange={(e) => setViewMode(e.target.checked ? 'tree' : 'list')}
                  size="small"
                />
              }
              label="树形视图"
            />
            <Button
              variant="contained"
              startIcon={<AddIcon />}
              onClick={() => setCreateDialogOpen(true)}
            >
              创建部门
            </Button>
            <IconButton onClick={handleMenuClick}>
              <MoreVertIcon />
            </IconButton>
            <Menu
              anchorEl={anchorEl}
              open={Boolean(anchorEl) && !selectedDepartment}
              onClose={handleMenuClose}
            >
              <MenuItem onClick={() => {
                queryClient.invalidateQueries({ queryKey: ['departments'] });
                handleMenuClose();
              }}>
                <RefreshIcon sx={{ mr: 1 }} />
                刷新数据
              </MenuItem>
              <MenuItem onClick={handleMenuClose}>
                <DownloadIcon sx={{ mr: 1 }} />
                导出部门
              </MenuItem>
              <MenuItem onClick={handleMenuClose}>
                <UploadIcon sx={{ mr: 1 }} />
                导入部门
              </MenuItem>
            </Menu>
          </Box>
        }
      />

      {/* 搜索和筛选 */}
      <Card sx={{ mb: 3 }}>
        <CardContent>
          <Grid container spacing={2} alignItems="center">
            <Grid item xs={12} md={4}>
              <TextField
                fullWidth
                placeholder="搜索部门名称、代码或描述..."
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                InputProps={{
                  startAdornment: <SearchIcon sx={{ color: 'text.secondary', mr: 1 }} />
                }}
              />
            </Grid>
            <Grid item xs={12} md={3}>
              <FormControl fullWidth>
                <InputLabel>状态</InputLabel>
                <Select
                  value={selectedStatus}
                  label="状态"
                  onChange={(e) => setSelectedStatus(e.target.value as string)}
                >
                  <MenuItem value="all">全部状态</MenuItem>
                  <MenuItem value="active">正常</MenuItem>
                  <MenuItem value="inactive">停用</MenuItem>
                </Select>
              </FormControl>
            </Grid>
            <Grid item xs={12} md={2}>
              <Button
                fullWidth
                variant="outlined"
                startIcon={viewMode === 'tree' ? <AccountTreeIcon /> : <ViewListIcon />}
                onClick={() => setViewMode(viewMode === 'tree' ? 'list' : 'tree')}
              >
                {viewMode === 'tree' ? '列表视图' : '树形视图'}
              </Button>
            </Grid>
            <Grid item xs={12} md={3}>
              <Typography variant="body2" color="text.secondary" align="right">
                共 {departments.length} 个部门，显示 {filteredDepartments.length} 个
              </Typography>
            </Grid>
          </Grid>
        </CardContent>
      </Card>

      {/* 部门列表 */}
      {isLoading ? (
        <Card>
          <CardContent>
            <Typography>加载中...</Typography>
          </CardContent>
        </Card>
      ) : (
        <Card>
          <CardContent>
            {viewMode === 'tree' ? (
              departmentTree.length > 0 ? (
                <TreeView
                  defaultCollapseIcon={<ExpandMoreIcon />}
                  defaultExpandIcon={<ChevronRightIcon />}
                  expanded={expandedNodes}
                  onNodeToggle={(event, nodeIds) => setExpandedNodes(nodeIds)}
                >
                  {departmentTree.map(node => renderTreeNode(node))}
                </TreeView>
              ) : (
                <Alert severity="info">暂无部门数据，请创建第一个部门</Alert>
              )
            ) : (
              filteredDepartments.length > 0 ? (
                renderListView()
              ) : (
                <Alert severity="info">暂无符合条件的部门</Alert>
              )
            )}
          </CardContent>
        </Card>
      )}

      {/* 部门操作菜单 */}
      <Menu
        anchorEl={anchorEl}
        open={Boolean(anchorEl) && Boolean(selectedDepartment)}
        onClose={handleMenuClose}
      >
        <MenuItem onClick={() => {
          navigate(`/departments/${selectedDepartment?.id}/edit`);
          handleMenuClose();
        }}>
          <EditIcon sx={{ mr: 1 }} />
          编辑部门
        </MenuItem>
        <MenuItem onClick={() => {
          setCreateDialogOpen(true);
          setValue('parentId', selectedDepartment?.id || '');
          handleMenuClose();
        }}>
          <AddIcon sx={{ mr: 1 }} />
          创建子部门
        </MenuItem>
        <Divider />
        <MenuItem 
          onClick={() => {
            setDeleteDialogOpen(true);
            handleMenuClose();
          }}
          sx={{ color: 'error.main' }}
        >
          <DeleteIcon sx={{ mr: 1 }} />
          删除部门
        </MenuItem>
      </Menu>

      {/* 创建部门对话框 */}
      <Dialog
        open={createDialogOpen}
        onClose={() => {
          setCreateDialogOpen(false);
          reset();
        }}
        maxWidth="md"
        fullWidth
      >
        <DialogTitle>创建部门</DialogTitle>
        <form onSubmit={handleSubmit(handleCreateDepartment)}>
          <DialogContent>
            <Grid container spacing={2} sx={{ mt: 1 }}>
              <Grid item xs={12} sm={6}>
                <Controller
                  name="name"
                  control={control}
                  rules={{ required: '部门名称不能为空' }}
                  render={({ field }) => (
                    <TextField
                      {...field}
                      label="部门名称"
                      fullWidth
                      error={!!errors.name}
                      helperText={errors.name?.message}
                    />
                  )}
                />
              </Grid>
              <Grid item xs={12} sm={6}>
                <Controller
                  name="code"
                  control={control}
                  rules={{ required: '部门代码不能为空' }}
                  render={({ field }) => (
                    <TextField
                      {...field}
                      label="部门代码"
                      fullWidth
                      error={!!errors.code}
                      helperText={errors.code?.message || '系统唯一标识，建议使用大写字母'}
                    />
                  )}
                />
              </Grid>
              <Grid item xs={12}>
                <Controller
                  name="description"
                  control={control}
                  render={({ field }) => (
                    <TextField
                      {...field}
                      label="部门描述"
                      fullWidth
                      multiline
                      rows={3}
                      placeholder="描述该部门的职能和责任"
                    />
                  )}
                />
              </Grid>
              <Grid item xs={12} sm={6}>
                <Controller
                  name="parentId"
                  control={control}
                  render={({ field }) => (
                    <FormControl fullWidth>
                      <InputLabel>上级部门</InputLabel>
                      <Select {...field} label="上级部门">
                        <MenuItem value="">无（作为顶级部门）</MenuItem>
                        {departments.map((dept: Department) => (
                          <MenuItem key={dept.id} value={dept.id}>
                            {dept.name}
                          </MenuItem>
                        ))}
                      </Select>
                    </FormControl>
                  )}
                />
              </Grid>
              <Grid item xs={12} sm={6}>
                <Controller
                  name="status"
                  control={control}
                  render={({ field }) => (
                    <FormControl fullWidth>
                      <InputLabel>状态</InputLabel>
                      <Select {...field} label="状态">
                        <MenuItem value="active">正常</MenuItem>
                        <MenuItem value="inactive">停用</MenuItem>
                      </Select>
                    </FormControl>
                  )}
                />
              </Grid>
            </Grid>
          </DialogContent>
          <DialogActions>
            <Button
              onClick={() => {
                setCreateDialogOpen(false);
                reset();
              }}
            >
              取消
            </Button>
            <Button
              type="submit"
              variant="contained"
              disabled={!isValid || createDepartmentMutation.isPending}
            >
              {createDepartmentMutation.isPending ? '创建中...' : '创建'}
            </Button>
          </DialogActions>
        </form>
      </Dialog>

      {/* 删除确认对话框 */}
      <Dialog
        open={deleteDialogOpen}
        onClose={() => setDeleteDialogOpen(false)}
      >
        <DialogTitle>删除部门</DialogTitle>
        <DialogContent>
          <Typography>
            确认删除部门 "{selectedDepartment?.name}"？
          </Typography>
          <Alert severity="warning" sx={{ mt: 2 }}>
            删除部门将同时删除其下所有子部门，该操作不可恢复！
          </Alert>
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setDeleteDialogOpen(false)}>
            取消
          </Button>
          <Button
            onClick={handleDeleteDepartment}
            color="error"
            variant="contained"
            disabled={deleteDepartmentMutation.isPending}
          >
            {deleteDepartmentMutation.isPending ? '删除中...' : '确认删除'}
          </Button>
        </DialogActions>
      </Dialog>
    </Box>
  );
};

export default DepartmentListPage;